<?php

namespace app\admin\controller\users;

use app\common\controller\Backend;

use app\admin\model\Vuearea;
use app\admin\model\User;
use app\admin\model\Worktype;
use think\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class Information extends Backend
{

    /**
     * Information模型对象
     * @var \app\admin\model\Information
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Information;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看[改造]
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['type', 'user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('type')->directors;
                $row->getRelation('type')->managers;
            }
            $data = ["total" => $list->total(), "rows" => $list->items()];
            $result = array('code' => 1, 'msg' => '成功', 'wait' => '3', 'data' => $data);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加[改造]
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->conversion2str(json_decode($this->request->post('data'), true));
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑[改造]
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->assign('row', $row); //兼容旧组件
            $this->assignconfig('row', $row);
            return $this->view->fetch();
        }
        $params = $this->conversion2str(json_decode($this->request->post('data'), true));
        $data = json_decode($this->request->post('data'), true);
        $state = $data['state'];
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            //审核通过
            if ($state == 1) {
                User::where('id', $row->user_id)->update([
                    'username' => $row->username,
                    'gender' => $row->gender,
                    'birthday' => $row->birthday,
                    'native_place' => $row->native_place,
                    'address' => $row->address,
                    'work_unit' => $row->work_unit,
                    'linkman' => $row->linkman,
                    'linkman_phone' => $row->linkman_phone,
                    'work_type' => $row->work_type,
                    'id_card' => $row->id_card,
                    'education' => $row->education,
                    'id_card_front' => $row->id_card_front,
                    'state' => 0,
                    'age' => $row->age,
                    'id_card_back' => $row->id_card_back,
                    'mobile' => $row->mobile,
                    'one_inch_photo' => $row->one_inch_photo,
                ]);
            }
            if ($state == 2) {
                User::where('id', $row->user_id)->update([
                    'state' => 0,
                ]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 数组转化为字符串[改造]
     *
     * @param $data
     * @return array
     * @throws DbException
     * @throws \think\Exception
     */
    function conversion2str($data)
    {
        $json_fields = [];
        if (!$data) {
            $this->error(__('No Results were found'));
        }
        foreach ($data as $key => &$items) {
            if (is_array($items)) {
                if (in_array($key, $json_fields)) {
                    $items = json_encode($items);
                } else {
                    $items = implode(',', $items);
                }

            }
        }
        return $data;

    }

    /**
     * 读取省市区数据,包含子数据，全部读取
     */
    function area_select()
    {
        $ids = $this->request->get();
        $area = cache('area-cascader');
        $area = Vuearea::cache(true)->with('children.children')->where('level', 1)->order('id asc')->select();

        if ($this->request->isAjax()) {
            $this->success('省市区列表', null, $area);
        }
        $this->assignconfig('areaData', $area);
        return $this->view->fetch();
    }
    public function export()
    {
        $id = $this->request->post('id');
        $info = $this->model->where('id',$id)->find();
        $worktype = Worktype::where('id',$info->work_type)->find();
        // 创建一个新的Excel对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        // 设置表头
        $sheet->setCellValue('A1', '姓名');
        $sheet->setCellValue('A2', '年龄');
        $sheet->setCellValue('A3', '性别');
        $sheet->setCellValue('A4', '一寸照');
        $sheet->setCellValue('A5', '手机号');
        $sheet->setCellValue('A6', '身份证号');
        $sheet->setCellValue('A7', '出生日期');
        $sheet->setCellValue('A8', '籍贯');
        $sheet->setCellValue('A9', '现住址');
        $sheet->setCellValue('A10', '工作单位');
        $sheet->setCellValue('A11', '单位联系人');
        $sheet->setCellValue('A12', '单位联系人电话');
        $sheet->setCellValue('A13', '工种');
        $sheet->setCellValue('A14', '负责人');
        $sheet->setCellValue('A15', '安全管理人');
        $sheet->setCellValue('A16', '身份证国徽面');
        $sheet->setCellValue('A17', '身份证人像面');
        $sheet->setCellValue('A18', '学历证明');
        $sheet->getColumnDimension('A')->setWidth(25); // 设置B列宽度为30
        $sheet->getColumnDimension('B')->setWidth(25); // 设置B列宽度为30
        $sheet->getRowDimension(4)->setRowHeight(80); // 设置第一行的行高为40
        $sheet->getRowDimension(16)->setRowHeight(80); // 设置第一行的行高为40
        $sheet->getRowDimension(18)->setRowHeight(80); // 设置第一行的行高为40
        $sheet->getRowDimension(17)->setRowHeight(80); // 设置第一行的行高为40
        $drawing = new Drawing();
//        $drawing->setName('一寸照');
//        $drawing->setDescription('一寸照');
        $info->one_inch_photo =  substr($info->one_inch_photo,1);
        $drawing->setPath($info->one_inch_photo); // 设置图片路径
        $drawing->setCoordinates('B4'); // 设置插入的单元格
        $drawing->setHeight(100); // 设置图片高度
//        $drawing->setName('身份证国徽面');
//        $drawing->setDescription('身份证国徽面');
        $drawing->setWorksheet($sheet);
        $drawing = new Drawing();
        $info->id_card_front =  substr($info->id_card_front,1);
        $drawing->setPath( $info->id_card_front); // 设置图片路径
        $drawing->setCoordinates('B16'); // 设置插入的单元格
//        $drawing->setName('身份证人像面');
//        $drawing->setDescription('身份证人像面');
        $drawing->setHeight(100); // 设置图片高度
        $drawing->setWorksheet($sheet);
        $drawing = new Drawing();
        $info->id_card_back =  substr($info->id_card_back,1);
        $drawing->setPath( $info->id_card_back); // 设置图片路径
        $drawing->setCoordinates('B17'); // 设置插入的单元
        $drawing->setHeight(100); // 设置图片高度
        $drawing->setWorksheet($sheet);
//        $drawing->setName('学历证明');
//        $drawing->setDescription('学历证明');
        $drawing = new Drawing();
        $info->education =  substr($info->education,1);
        $drawing->setPath( $info->education); // 设置图片路径
        $drawing->setCoordinates('B18'); // 设置插入的单元格
        $drawing->setHeight(100); // 设置图片高度
        $drawing->setWorksheet($sheet);
        $sheet->setCellValue('B1', $info->username);
        $sheet->setCellValue('B2', $info->age);
        $sheet->setCellValue('B3',  $info->gender);
//        $sheet->setCellValue('B4', $info->one_inch_photo);
        $sheet->setCellValue('B5', $info->mobile);
        $sheet->setCellValue('B6', $info->id_card);
        $sheet->setCellValue('B7', $info->birthday);
        $sheet->setCellValue('B8',  $info->native_place);
        $sheet->setCellValue('B9', $info->address);
        $sheet->setCellValue('B10', $info->work_unit);
        $sheet->setCellValue('B11', $info->linkman);
        $sheet->setCellValue('B12', $info->linkman_phone);
        $sheet->setCellValue('B13', $worktype->name);
        $sheet->setCellValue('B14', $worktype->directors->username);
        $sheet->setCellValue('B15',$worktype->managers->username);
//        $sheet->setCellValue('B16', $info->id_card_front);
//        $sheet->setCellValue('B17', $info->id_card_back);
//        $sheet->setCellValue('B18', $info->education);
        // 保存为Excel文件
        $file_name = 'export_' . time() . '.xlsx';
        $save_path = 'uploads/execl/';
        // 创建目录（如果不存在）
        if (!file_exists($save_path)) {
            mkdir($save_path, 0777, true); // 创建多级目录，确保目录存在并有适当的权限
        }
        // 完整文件路径
        $file_path = $save_path . $file_name;
        $writer = new Xlsx($spreadsheet);
        $writer->save($file_path);
        $this->deleteFileLater($file_path, 60);

        $this->success('请注意浏览器下载列表','/'.$file_path);
    }
    private function deleteFileLater($filePath, $seconds) {
        // 通过定时任务或者其他方式在指定时间后删除文件
        sleep($seconds);
        unlink($filePath);
    }
}
